import { randomString, deepClone } from "@/plugins/unit";

// 单元组件处理类
export default class UnitViewHandle {
    $view

    constructor(view) {
        this.$view = view
    }

    // 增
    add(findKey, newView) {
        let res = this.findUnit(this.$view, findKey)
        res.slot.children.push({
            ...newView,
            key: randomString(6),
        })
        return this.$view
    }

    // 删除一个元素
    // tips 数据中的最外层元素不能删除
    del(findKey) {
        if (findKey === this.$view.key) return
        let { i, target } = this.findUnitParent(this.$view, findKey)
        target.slot.children.splice(i, 1)
        return this.$view
    }

    // 修改props
    set(target) {
        let { key, props, slot } = target
        let res = this.findUnit(this.$view, key)
        res.props = props;
        res.slot = slot;
        return this.$view
    }

    // 查
    get(findKey) { }

    // 寻找出对应key值的数据的元素
    findUnit(current, findKey) {
        const { key, slot: { children } } = current;
        let result;

        // 是当前元素就返回
        if (key == findKey) {
            result = current;
        } else if (children && Array.isArray(children)) {
            for (const item of children) {
                let child = this.findUnit(item, findKey);
                child && (result = child);
            }
        }

        return result;
    }

    // 寻找出对应key元素的父元素
    findUnitParent(current, findKey) {
        const { slot: { children } } = current;
        let result;

        if (children && Array.isArray(children)) {
            for (const i in children) {
                if (children.hasOwnProperty(i)) {
                    const item = children[i];
                    if (item.key === findKey) {
                        result = { target: current, i }
                    } else {
                        let child = this.findUnit(item, findKey);
                        child && (result = child);
                    }
                }
            }

        }

        return result;
    }
} 